package com.fingard.dsp.bank.directbank.ynrcc01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/5/10.
 */
public class YNRCC01Base extends DirectBase implements ITcpClient {
    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 6) {
                String tmpHead = new String(p_receiver.recBytes, 0, 6, getCharset());
                WriteBankLogStep3(tmpHead);
                p_receiver.contentLength = Integer.parseInt(tmpHead.trim())-31;
                p_receiver.contentStartIndex = 31;
            }
        }
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    /**
     *
     * @param p_reqStr  报文数据
     * @return
     */
    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        String url="http://"+bankFront.serverIP+":"+bankFront.serverPort+"/YNRCB_B2EF/B2EController";
        WriteBankUrlLogLn( "请求银行的地址"+url);
        p_reqStr=p_reqStr.replaceAll("\r","").replaceAll("\n","");
        p_reqStr=p_reqStr.substring(0,p_reqStr.indexOf("<Message>"))+p_reqStr.substring(p_reqStr.indexOf("<Message>")).replaceAll(" ","");
        WriteBankLogLn("发送至银行的报文："+p_reqStr);
        //发送银行前置
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //tmpWebRequest.setRequestProperty("connection", "Close");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    protected void wirteCommenHeader(XmlTextWriter xmlTextWriter, YNRCC01Header header) {
        xmlTextWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
        xmlTextWriter.writeStartElement("Message");
        xmlTextWriter.writeStartElement("Head");
        xmlTextWriter.writeElementString("TransCode", header.transCode);
        xmlTextWriter.writeElementString("ERPTrsTimestamp", Format.DateTime14Format.format(new Date()));
        xmlTextWriter.writeElementString("ERPJnlNo", header.erpJnlNo);
        xmlTextWriter.writeElementString("TrsFlag", "0");
        xmlTextWriter.writeEndElement();
    }
}
